﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace AdaNNTP
{
    internal static class yEncoding
    {

        private static yEncMessage ProcessYencBody(string originalAttachment)
        {
            //A dirty way of breaking up the original attachment, but it works.
            string[] messageLines = originalAttachment..Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            yEncMessage finalMessage = new yEncMessage();

            //The first line of the body will be the header. The rest? Actual content. Except for the last line, which is more metadata.
            if (messageLines[0].StartsWith(@"=ybegin"))
            {
                finalMessage.ParseHeader(messageLines[0]);

                if (messageLines[(messageLines.Count() - 1)].StartsWith(@"=yend"))
                    finalMessage.ParseFooter(messageLines[(messageLines.Count() - 1)]);
                else
                    throw new InvalidDataException("Bad yEnc attachment: " + originalAttachment);  

                StringBuilder messageBuilder = new StringBuilder();
                for (int i = 1; i < messageLines.Count() - 2; ++i)
                {
                    messageBuilder.Append(messageLines[i]);
                }

                yEnc.YEncDecoder yEncDecoderType = new yEnc.YEncDecoder();

                MemoryStream ms = new MemoryStream(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(messageBuilder.ToString()));
                CryptoStream yEncCryptoStream = new CryptoStream(ms, yEncDecoderType, CryptoStreamMode.Read);
                StreamReader r = new StreamReader(yEncCryptoStream);

                finalMessage.Contents = r.ReadToEnd();

                return finalMessage;
            }
            else
            {
                throw new InvalidDataException("Bad yEnc attachment: " + originalAttachment);
            }
        }
        public static yEncMessage ProcessYencAttachment(AdaNNTP.File originalAttachment)
        {
            
        }

        internal sealed class yEncMessage
        {
            public string Filename { get; set; }

            public int Size { get; set; }

            public int Lines { get; set; }

            public string CRC32 { get; set; }

            public string Contents { get; set; }

            public yEncMessage ParseHeader(string input)
            {
                this.Filename = input.Substring(input.IndexOf("name="), input.Length - input.IndexOf("name=")).Replace("name=", string.Empty);
                //this.Size = int.Parse(input.Substring(input.IndexOf("size="), (input.IndexOf(' ', input.IndexOf("size=")) - input.IndexOf("size="))));
                

                return this;
            }

            public yEncMessage ParseFooter(string input)
            {
                string[] tokens = input.Split(' ');

                foreach (string token in tokens)
                {
                    string[] subTokens = token.Split('=');

                    switch (subTokens[0])
                    {
                        case "yend":
                            break;
                        /*case "size":
                            if (int.Parse(subTokens[1]) != this.Size)
                                throw new InvalidDataException("yEnc Header & Footer disagree on size");
                            break;*/
                        case "crc32":
                            this.CRC32 = subTokens[1];
                            break;
                        default:
                            Console.WriteLine("Unexpected token in yEnc header: " + subTokens[0]);
                            break;
                    }
                }

                return this;
            }

        }
    }
}
